package com.web.dao.category;

import com.web.bean.category.Category;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @autor Chen
 * @create 2021--25-11:17
 * @desc
 */
public class CategoryDaoImpl implements CategoryDao{
    private Connection connection;
    private PreparedStatement pst;
    private ResultSet rs;

    public CategoryDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Category> selectCategories() throws Exception {
        List<Category> categories = new ArrayList<>();
        String sql = "select * from wn_dictionaries";
        pst = connection.prepareStatement(sql);
        rs = pst.executeQuery();
        while (rs.next()) {
            Category category = new Category();
            category.setCategory(rs.getString(1));
            category.setCode(rs.getString(2));
            categories.add(category);
        }
        return categories;
    }

    @Override
    public Category selectByCode(String code) throws Exception {
        Category category = new Category();
        String sql = "select * from wn_dictionaries where code = ?";
        pst = connection.prepareStatement(sql);
        pst.setObject(1, code);
        rs = pst.executeQuery();
        while (rs.next()) {
            category.setCategory(rs.getString(1));
            category.setCode(rs.getString(2));
        }
        return category;
    }

    @Override
    public void addCategory(Category category) throws Exception {
        String sql="insert into wn_dictionaries values(????????)";
        pst=connection.prepareStatement(sql);
        pst.setString(1,category.getCategory());
        pst.setString(2,category.getCode());
        pst.executeUpdate();

    }

    @Override
    public void deleteCategory(String code) throws Exception {
        String sql="delete from wn_dictionaries where code=?";
        pst=connection.prepareStatement(sql);
        pst.setObject(1,code);
        pst.executeUpdate();

    }
}
